package cn.datawin.service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.googlecode.jsonplugin.JSONUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import cn.datawin.bean.page.ReqData;
import cn.datawin.bean.page.RespData;
import cn.datawin.dao.BaseDao;

/**
 * 基础业务, 通用业务service
 * @author Administrator
 * 
 */
public class BaseService extends BaseDao {
	public static Map<String, Integer> sortmap = new HashMap<String, Integer>(2);
	static{
		sortmap.put("asc", 1);
		sortmap.put("desc", -1);
	}

	public RespData<List<DBObject>> page(String col, DBObject query, ReqData reqData) {
		RespData<List<DBObject>> respData = new RespData<List<DBObject>>();
		int start = (reqData.getPage() - 1) * reqData.getRows();
		BasicDBObject sort = null;
		if(reqData.getSort()!=null){
			sort = new BasicDBObject(reqData.getSort(), sortmap.get(reqData.getOrder())); 
		}
		List<DBObject> rows = super.findList(col, query, sort, start, reqData.getRows());
		respData.setRows(rows);
		respData.setTotal(super.count(col, query));
		return respData;
	}
	
	
	public RespData<List<DBObject>> parseObjectId(RespData<List<DBObject>> respData, String... key){
		parseObjectId(respData.getRows(),key);
		return respData;
	}

	public DBObject objectId2str(DBObject dbObject, String... key) {
		for(String k: key){
			dbObject.put(k, dbObject.removeField(k).toString());
		}
		return dbObject;
	}

	public List<DBObject> parseObjectId(List<DBObject> list, String... key) {
		for (DBObject dbo : list) {
			objectId2str(dbo, key);
		}
		return list;
	}

	public static Object deserialize(String json){
		try{
			return JSONUtil.deserialize(json);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static String serialize(Object obj){
		try{
			return JSONUtil.serialize(obj);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
